package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysMenuDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.mapper.SysMenuMapper;
import com.itheima.ydd.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Slf4j
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    public ResultData allData() {
        List<SysMenu> list = super.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPid, 0));
        List<SysMenuDto> menuDtoList = list.stream().map(item -> {
            SysMenuDto menuDto = new SysMenuDto();
            BeanUtils.copyProperties(item, menuDto);
            childList(menuDto);
            return menuDto;
        }).collect(Collectors.toList());

        return ResultData.ok("0", menuDtoList);

    }


    @Override
    public void childList(SysMenuDto menuDto) {
        List<SysMenu> list = super.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPid, menuDto.getId()));
        if (list.isEmpty()) {
            return;
        }

        List<SysMenu> collect = list.stream().map(item -> {
            SysMenuDto childMenuDto = new SysMenuDto();
            BeanUtils.copyProperties(item, childMenuDto);
            childList(childMenuDto);
            return childMenuDto;
        }).collect(Collectors.toList());
        menuDto.setChildren(collect);
    }

    @Override
    public void del(Integer id) {
        //判断是否存在子菜单
        LambdaQueryWrapper<SysMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysMenu::getPid, id);
        List<SysMenu> list = list(lqw);
        if (list.size() > 0) {
            //若存在则不删除
            throw new BusinessException("存在子目录,不能删除");
        }
        //若不存在则根据id删除
        removeById(id);
    }
}
